from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.DbTools import DbTools
from util.DataQuery.FormDataDecorator import FormDataDecorator
from util.g import g


class WritePSForm():
    form_btn_loc = (By.LINK_TEXT, '上年度高新技术产品（服务）情况表')
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")

    #    添加按钮
    # add_btn_loc = (By.CSS_SELECTOR, '.form-group.pull-right .blue')
    add_btn_loc = (By.XPATH, "//div[@class='form-group pull-right']/button[contains(string(), '添加')]")
    #    删除按钮
    # delete_btn_loc = (By.CSS_SELECTOR, '.table-search div:nth-of-type(2) button')
    delete_btn_loc = (By.XPATH, "//div[@class='form-group pull-right']/button[contains(string(), '删除')]")

    ps_num_loc = (By.CSS_SELECTOR, 'input#cod')
    ps_pro_name_loc = (By.CSS_SELECTOR, 'input#productName')
    ps_domain1_loc = (By.CSS_SELECTOR, 'select#onemain')
    ps_domain2_loc = (By.CSS_SELECTOR, 'select#scdmain')
    ps_domain3_loc = (By.CSS_SELECTOR, 'select#thdmain')
    # 技术来源 ------ 字典值 ------- tech_source
    ps_source_loc = (By.CSS_SELECTOR, 'select#technologyS')
    ps_sale_loc = (By.CSS_SELECTOR, 'input#shr')
    is_main_server = (By.CSS_SELECTOR, 'input#checkbox_yes')
    no_main_server = (By.CSS_SELECTOR, 'input#checkbox_no')
    ipr_ids_loc = (By.CSS_SELECTOR, "select#Zscqbh")
    ipr_ids_value_loc = (By.CSS_SELECTOR, 'textarea#yxZscqbh')
    ipr_ids_value_js_str = "document.getElementById('yxZscqbh').removeAttribute('readonly')"
    keytech_ind_loc = (By.CSS_SELECTOR, 'textarea#PGjjszb')
    caosp_loc = (By.NAME, 'dataEprProduct.Pjzys')
    aipr_tsp_loc = (By.CSS_SELECTOR, 'textarea#PZscqqk')

    upload_btn_loc = (By.CSS_SELECTOR, '.uploadAttachment a')
    # # # 保存按钮
    back_btn_loc = (By.CSS_SELECTOR, '.box-footer.text-right button.btn-default')
    # # # 保存按钮
    save_btn_loc = (By.CSS_SELECTOR, '.box-footer.text-right button#eprproductsave')

    next_page_loc = (By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(4) a")

    page_num_loc = (By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(3) a")
    select_all_loc = (By.CSS_SELECTOR, "input#items_selector")

    delete = False
    def __init__(self, driver=None):
        self.driver = driver
        setattr(g, self.class_name, list())
    @property
    def class_name(self):
        return self.__class__.__name__

    def input_num_name(self, ps_id, ps_name):
        # # 不够两位的， 自动在前面补个 0.
        ps_id = str(ps_id).zfill(2)
        BM.input(ele_loc=self.ps_num_loc, driver=self.driver, keys=ps_id)
        BM.input(ele_loc=self.ps_pro_name_loc, driver=self.driver, keys=ps_name)

    @classmethod
    def get_domain_by_namelist(cls, hitech_field_namelist=""):
        return hitech_field_namelist.split(",")

    def input_tech_info(self, tech_fieldname, tech_fieldlist, tech_source, sales_revenue):
        if tech_fieldname is None:
            hitech_fields = DbTools.get_hitech_name_by_ids(ids=tech_fieldlist)
            hitech_ = {i.get("id"): i.get("name") for i in hitech_fields}
            tech_fieldname = ",".join([hitech_.get(int(i)) for i in tech_fieldlist.split(",")])
        domain_num = len(tech_fieldname.split(","))
        domain1, domain2, domain3, domain4 = None, None, None, None
        if domain_num == 2:
            domain1, domain2 = self.get_domain_by_namelist(hitech_field_namelist=tech_fieldname)
            domain3 = "无"
            tech_fieldname += ",无"
        if domain_num == 3:
            domain1, domain2, domain3 = self.get_domain_by_namelist(hitech_field_namelist=tech_fieldname)
        elif domain_num == 4:
            domain1, domain2, domain3, domain4 = self.get_domain_by_namelist(hitech_field_namelist=tech_fieldname)

        # BM.select_value(driver=self.driver, ele_loc=self.domain1_loc, keys=domain1)
        # BM.select_value(driver=self.driver, ele_loc=self.domain2_loc, keys=domain2)
        # BM.select_value(driver=self.driver, ele_loc=self.domain3_loc, keys=domain3)
        # domain1, domain2, domain3 = tech_fieldname.split(',')
        BM.select_domain(selector_loc=self.ps_domain1_loc, text_value=domain1, driver=self.driver, tech_fieldname=tech_fieldname)
        BM.select_domain(selector_loc=self.ps_domain2_loc, text_value=domain2, driver=self.driver, tech_fieldname=tech_fieldname)
        BM.select_domain(selector_loc=self.ps_domain3_loc, text_value=domain3, driver=self.driver, tech_fieldname=tech_fieldname)
        # 选取技术来源
        BM.select_value_choice(selector_loc=self.ps_source_loc, text_value=tech_source, driver=self.driver)
        BM.input(ele_loc=self.ps_sale_loc, driver=self.driver, keys=sales_revenue)

    def input_product_info(self, is_major, ipr_ids):
        if is_major: BM.click(driver=self.driver, ele_loc=self.is_main_server)
        else: BM.click(driver=self.driver, ele_loc=self.no_main_server)

        # ipr_str = '\n'.join(['IP' + i.zfill(2) for i in ipr_ids.split(',') if i])
        # self.driver.execute_script(self.ipr_ids_value_js_str)
        # BM.input(ele_loc=self.ipr_ids_value_loc, driver=self.driver, keys=ipr_str)
        for ip in ipr_ids.split(","):
            ip_s = "IP" + ip.zfill(2) if ip != 0 else "其他"
            BM.select_value_choice(selector_loc=self.ipr_ids_loc, driver=self.driver, text_value=ip_s)

    def input_long_text(self, keytech_ind, caosp, aipr_tsp):
        BM.input_textarea_info(ele_loc=self.keytech_ind_loc, driver=self.driver, keys=keytech_ind)
        BM.input_textarea_info(ele_loc=self.caosp_loc, driver=self.driver, keys=caosp)
        BM.input_textarea_info(ele_loc=self.aipr_tsp_loc, driver=self.driver, keys=aipr_tsp)

    def click_save_btn(self):
        return BM.global_click_btn(btn_loc=self.save_btn_loc, driver=self.driver)

    @FormDataDecorator
    def main(self, ps_id='', ps_name='', tech_fieldname='', tech_fieldlist="", tech_source='', sales_revenue='', is_major=1,
                      ipr_ids='', keytech_ind='', caosp='', aipr_tsp=''):
        # BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
        # if g.is_first_entry and self.delete:
        #     BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
        #     BM.delete_all(driver=self.driver, page_num_loc=self.page_num_loc, select_all_loc=self.select_all_loc, delete_btn_loc=self.delete_btn_loc)
        #     self.delete = True
        is_click = False
        class_name = self.class_name
        if getattr(g, class_name) == []:
            is_click = True
            BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
            BM.cut_over_frame(driver=self.driver, selector_loc=self.content_iframe_loc)
            a_list = getattr(g, class_name)
            table_loc = (By.CSS_SELECTOR, ".tableBody")
            tr_loc = (By.CSS_SELECTOR, ".tableBody tr td:nth-of-type(3)")

            while True and g.repetition:
                BM.wait(driver=self.driver, ele_loc=table_loc)
                data = self.driver.find_elements(*tr_loc)
                for i in data:
                    # 获取 标签中的 汉字
                    sta_name_str = i.text
                    a_list.append(sta_name_str)


                next_btn = BM.get_ele(driver=self.driver, ele_loc=self.next_page_loc)
                onclick = next_btn.get_attribute("onclick")
                if not onclick:
                    # BM.click(driver=self.driver, ele_loc=self.next_page_loc)
                    break
                else:
                    next_btn.click()
        li_list = getattr(g, class_name)
        # g.logger.info("{}： {}".format(class_name, li_list))
        if ps_name in li_list and g.repetition:
            g.logger.info("{} ----- {} 已存在".format(class_name, ps_name))
            return
        g.logger.info("{}： {}".format(class_name, li_list))

        # if not is_click:
        #     BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
        # if g.repetition and not self.delete:
        #     BM.delete_all(driver=self.driver, page_num_loc=self.page_num_loc, select_all_loc=self.select_all_loc, delete_btn_loc=self.delete_btn_loc)
        #     self.delete = True
        BM.wait(driver=self.driver, ele_loc=self.add_btn_loc)
        BM.click(driver=self.driver, ele_loc=self.add_btn_loc)
        BM.wait(driver=self.driver, ele_loc=self.save_btn_loc)
        self.input_num_name(ps_id=ps_id, ps_name=ps_name)
        self.input_tech_info(tech_fieldname=tech_fieldname, tech_fieldlist=tech_fieldlist, tech_source=tech_source, sales_revenue=sales_revenue)
        self.input_product_info(is_major=is_major, ipr_ids=ipr_ids)
        self.input_long_text(keytech_ind=keytech_ind, caosp=caosp, aipr_tsp=aipr_tsp)

        # # # TODO 上传附件
        BM.click_upload_attach(btn_loc=self.upload_btn_loc, driver=self.driver, class_name=self.class_name, _id=ps_id)
        res = self.click_save_btn()
        if res:
            li_list.append(ps_name)

        # click_back_btn(btn_loc=self.back_btn_loc, driver=self.driver)
